package net.zjitc.arrays.tree;

public class Demo {
    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7,8,9};
        int key=5;
        int index=serach(arr,key);
        System.out.println(index);
    }

    /**
     * 返回下标
     * @param arr
     * @param key
     * @return 成功：下标 失败：-1
     */
    private static int serach(int[] arr, int key) {
        int mid;
        int left=0;
        int right=arr.length-1;
        while (right>=left){
            mid=(right+left)/2;
            if (arr[mid]>key){//一定要在前半段
             right=mid-1;
            }else if(arr[mid]<key){//一定要在后半段
              left=mid+1;
            }else{//找到
                return mid;
            }
        }
        return -1;
    }
}
